﻿using JV.Com.Business;
using JV.Com.Internals;
using JV.Com.Model;
using JV.Com.Tools;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml.Documents;

namespace JV.Com.ViewModels
{
    public sealed class DetailFolderPageViewModel : PageBaseViewModel
    {
        private readonly FolderPageViewModel m_parent;
        private FolderPage m_page;
        private FolderPageNavigationParameter m_currentParameter;
        public DetailFolderPageViewModel(FolderPageViewModel parent, INavigationService navigationService)
            : base(navigationService)
        {
            m_page = new FolderPage();
            m_parent = parent;
        }

        public async override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);

            m_currentParameter = SerializerHelper.Deserialize<FolderPageNavigationParameter>((string)navigationParameter);

            InLoading = true;
            await UpdateFolderAsync(m_currentParameter.FolderId, m_currentParameter.FolderPage);
        }

        public event EventHandler FolderUpdatedEvent;
        public async Task UpdateFolderAsync(int folderId, int folderPage)
        {
            m_page = await Service.GetFolderPageAsync(folderId, folderPage);

            var converter = new Tools.HtmlToRichTextConverter(JV.Com.Tools.HtmlToRichTextConverter.ConvertType.FolderPage);
            var inlines = converter.GetHTMLInlineCollection(m_page.Content);
            m_paragraph = inlines.ToParagraph();

            m_parent.FolderPage = folderPage;
            m_parent.CanGoNextPage = m_page.NextPage.HasValue;
            m_parent.CanGoPrevPage = m_page.PrevPage.HasValue;
            m_parent.RaiseAllProperties();

            if (FolderUpdatedEvent != null) FolderUpdatedEvent(this, EventArgs.Empty);
        }

        private Paragraph m_paragraph;
        public Paragraph Paragraph { get { return m_paragraph; } }

        public override string PageTitle
        {
            get { throw new NotSupportedException(); }
        }

        public FolderPageViewModel Parent { get { return m_parent; } }

        //public override INavigationService GetMainNavigationService()
        //{
        //    return m_parent.NavigationService;
        //}
    }
}
